# Kestrel: An XMPP-based Many-Task Computing Scheduler
# Author: Lance Stout <lancestout@gmail.com>
#
# Copyright 2009-2010 Clemson University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from __future__ import with_statement
import threading
from time import time


class Kernel(object):
    """
    The kernel provides three functions for applications
    built on top of it: events, configuration, and logging.

    The event engine serves as the heart of the application,
    passing messages between modules and allows for 'roles'
    to be assumed and dropped by registering and unregistering
    module event handlers.

    Configuration is provided in a registry fashion. Items can
    be accessed and set using a path like notation to simplify
    access by other modules.

    The kernel also keeps track of the application's main log
    files and provides access to them.
    """

    def __init__(self, config=None, events=None):
        """
        Initialize the kernel's state.

        Provided configuration data must be a nested
        dictionary data structure.

        Event data must be a dictionary of event names
        mapping to lists of event handling functions.
        """
        if config is None:
            config = {}

        if events is None:
            events = {}

        self.events = events
        self.config_data = config
        self.lock = threading.Lock()

    def start(self, mode):
        """Begin event processing."""
        lifecycle = self.config('kernel/lifecycles/' + mode)
        if lifecycle is not None:
            lifecycle(self)
        self.event('kernel/start')

    def stop(self):
        """Stop event processing; clean up resources."""
        self.event('kernel/stop')

    def event(self, event_name, data=None):
        """Notify event listeners that an event has fired."""
        # As a temporary convenience, all events are logged
        # until a more robust logging method is implemented.
        self.log(event_name, data)
        for handler in self.events.get(event_name, []):
            handler(data)

    def register(self, module):
        """Register events from a new module."""
        for event in module.events:
            self.register_event(event, module.events[event])

    def register_event(self, event_name, handler):
        """
        Register a new event type and handler.

        Event handlers are passed a single argument.
        """
        if self.events.get(event_name, None) is None:
            self.events[event_name] = []

        self.events[event_name].append(handler)

    def unregister(self, module):
        """Remove event handlers from a module."""
        pass

    def config(self, path, default=None):
        """
        Access configuration item or return optional default
        if no item is found.

        Entries are formatted using slashes, for example:
        >>> kernel.config('system/state')
        """
        with self.lock:
            keys = path.split('/')
            val = self.config_data
            for key in keys:
                if val is None:
                    return default
                if type(val) is not dict:
                    return val
                val = val.get(key, default)

            return val

    def set_config(self, path, value):
        """
        Set the configuration item's value, or create a new
        item if one does not exist.

        Entries are formatted using slashes, for example:
        >>> kernel.set_config('system/state', 'busy')
        """
        with self.lock:
            keys = path.split('/')
            ref = self.config_data
            for key in keys:
                if key == '':
                    continue
                if type(ref) is not dict or ref.get(key, None) is None:
                    ref[key] = {}
                if key == keys[-1]:
                    ref[key] = value
                ref = ref[key]

    def log(self, level, message):
        """Write message to the application log."""
        with self.lock:
            if message is None:
                message = ''
            print "%0.2f [%s] %s\n" % (time(), level, str(message))
